package com.hx.reflect;


import com.hx.reflect.bean.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author jxlgcmh
 * @create 2019-05-11 09:39
 */
public class Demo1 {

    public static void main(String[] args) throws Exception {
        //通过new的方式实例化对象
//		Student s = new Student(1, "xiaoliu");

        //通过反射的方式
        Class<Student> clazz = Student.class;
        Constructor<Student> constructor = clazz.getConstructor(int.class, String.class);
        constructor.setAccessible(true);
        Student student = constructor.newInstance(1, "xiaohua");
//		System.out.println(student);
        //调用属性
        Field name = clazz.getDeclaredField("name");


        name.set(student, "lucy");
//		System.out.println(student);
        //调用方法
        Method showName = clazz.getDeclaredMethod("showName");
        //返回的name
//		Object invoke = showName.invoke(student);
//		System.out.println(invoke);
        Field id = clazz.getDeclaredField("id");
        //调用私有属性
        id.setAccessible(true);
        id.set(student, 9989);
//		System.out.println(student);
        //调用私有方法
        Method sayHi = clazz.getDeclaredMethod("sayHi");
        sayHi.setAccessible(true);
        sayHi.invoke(student);

    }
}
